package com.hgyc.mom.generator.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.common.util.FreeMarkerUtils;
import com.hgyc.mom.common.util.ObjectUtils;
import com.hgyc.mom.common.util.StringUtils;
import com.hgyc.mom.common.util.text.CharsetKit;
import com.hgyc.mom.generator.constant.GenConstants;
import com.hgyc.mom.generator.entity.GenTable;
import com.hgyc.mom.generator.entity.GenTableColumn;
import com.hgyc.mom.generator.entity.GenTableInfoVO;
import com.hgyc.mom.generator.entity.GenTableParam;
import com.hgyc.mom.generator.mapper.GenTableColumnMapper;
import com.hgyc.mom.generator.mapper.GenTableMapper;
import com.hgyc.mom.generator.service.GenTableColumnService;
import com.hgyc.mom.generator.service.GenTableService;
import com.hgyc.mom.generator.util.GenUtils;
import com.hgyc.mom.generator.util.TemplateUtils;
import freemarker.template.TemplateException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成表 服务层实现
 * 
 * @author fwj
 */
@Service
public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> implements GenTableService
{
    private static final Logger log = LoggerFactory.getLogger(GenTableServiceImpl.class);

    @Autowired
    private GenTableMapper genTableMapper;

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    @Autowired
    private GenTableColumnService genTableColumnService;

    /**
     * 查询业务信息
     * 
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(Long id) throws JsonProcessingException {
        GenTable genTable = genTableMapper.selectGenTableById(id);
        return genTable;
    }

    /**
     * 查询业务列表
     * 
     * @param genTable 业务信息
     * @return 业务集合
     */
    @Override
    public List<GenTable> selectGenTableList(GenTable genTable)
    {
        return genTableMapper.selectGenTableList(genTable);
    }

    /**
     * 查询据库列表
     * 
     * @param genTableParam 业务信息
     * @return 数据库表集合
     */
    @Override
    public IPage<GenTable> selectDbTableList(GenTableParam genTableParam)
    {
        Page<GenTable> page = new Page<>(genTableParam.getPage(), genTableParam.getPageSize());
        return genTableMapper.selectDbTableList(page, genTableParam);
    }

    /**
     * 查询据库列表
     * 
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    @Override
    public List<GenTable> selectDbTableListByNames(String[] tableNames)
    {
        return genTableMapper.selectDbTableListByNames(tableNames);
    }

    /**
     * 查询所有表信息
     * 
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll()
    {
        return genTableMapper.selectGenTableAll();
    }

    /**
     * 修改业务
     * 
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateGenTable(GenTableInfoVO genTable)
    {
        if (updateById(genTable))
        {
            for (GenTableColumn cenTableColumn : genTable.getColumns())
            {
                genTableColumnService.updateById(cenTableColumn);
            }
        }
    }

    /**
     * 删除业务对象
     * 
     * @param tableIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteGenTableByIds(Long[] tableIds)
    {
        genTableMapper.deleteGenTableByIds(tableIds);
        genTableColumnMapper.deleteGenTableColumnByIds(tableIds);
    }

    /**
     * 导入表结构
     * 
     * @param tableList 导入表列表
     */
    @Override
    @Transactional
    public void importGenTable(List<GenTable> tableList)
    {

        Long userId = ObjectUtils.toLong(StpUtil.getLoginId());

        try
        {
            for (GenTable table : tableList)
            {
                String tableName = table.getTableName();
                GenUtils.initTable(table, userId);
                Boolean saveSuccess = save(table);
                if (saveSuccess)
                {
                    // 保存列信息
                    List<GenTableColumn> genTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
                    for (GenTableColumn column : genTableColumns)
                    {
                        GenUtils.initColumnField(column, table);
                        genTableColumnService.save(column);
                    }
                }
            }
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
            throw new BizException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 预览代码
     * 
     * @param tableName 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(String tableName) throws JsonProcessingException {
        Map<String, String> dataMap = new LinkedHashMap<>();

        GenTableInfoVO genTableInfoVO = this.getGenTableInfo(tableName);

        Map<String, Object> context = TemplateUtils.prepareContext(genTableInfoVO);

        // 获取模板列表
        List<String> templates = TemplateUtils.getTemplateList(genTableInfoVO.getTplCategory());
        try {
            for (String template : templates)
            {
                // 渲染模板
                String templateStr = FreeMarkerUtils.processTemplate(template, context);
                dataMap.put(template, templateStr);
            }
        }catch (Exception e) {
            throw new BizException("生成代码失败", e);
        }

        return dataMap;
    }

    /**
     * 生成代码（下载方式）
     * 
     * @param tableName 表名称
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String tableName) throws TemplateException, IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码（自定义路径）
     * 
     * @param tableName 表名称
     */
    @Override
    public void generatorCode(String tableName) throws JsonProcessingException {
        GenTableInfoVO genTableInfoVO = this.getGenTableInfo(tableName);

        Map<String, Object> context = TemplateUtils.prepareContext(genTableInfoVO);

        // 获取模板列表
        List<String> templates = TemplateUtils.getTemplateList(genTableInfoVO.getTplCategory());
        for (String template : templates)
        {
            if (!StringUtils.containsAny(template, "sql.vm", "api.ts.vm", "index.vue.vm", "index-tree.vue.vm"))
            {
                try{
                    String templateStr = FreeMarkerUtils.processTemplate(template, context);
                    String path = getGenPath(genTableInfoVO, template);
                    FileUtils.writeStringToFile(new File(path), templateStr, CharsetKit.UTF_8);
                }
                catch (IOException e){
                    throw new BizException("渲染模板失败，表名：" + genTableInfoVO.getTableName());
                } catch (TemplateException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 同步数据库
     * 
     * @param tableName 表名称
     */
    @Override
    @Transactional
    public void synchDb(String tableName)
    {
        GenTable table = selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = genTableColumnService.selectGenTableColumnListByTableId(table.getTableId());
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::getColumnName, Function.identity()));

        List<GenTableColumn> dbTableColumns = genTableColumnMapper.selectDbTableColumnsByName(tableName);
        if (StringUtils.isEmpty(dbTableColumns))
        {
            throw new BizException("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());

        dbTableColumns.forEach(column -> {
            GenUtils.initColumnField(column, table);
            if (tableColumnMap.containsKey(column.getColumnName()))
            {
                GenTableColumn prevColumn = tableColumnMap.get(column.getColumnName());
                column.setColumnId(prevColumn.getColumnId());
                if (column.isList())
                {
                    // 如果是列表，继续保留查询方式/字典类型选项
                    column.setDictType(prevColumn.getDictType());
                    column.setQueryType(prevColumn.getQueryType());
                }
                if (prevColumn.isRequired()  && !column.isPk()
                        && (column.isInsert() || column.isEdit())
                        && ((column.isUsableColumn()) || (!column.isSuperColumn())))
                {
                    // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                    column.setIsRequired(prevColumn.getIsRequired());
                    column.setHtmlType(prevColumn.getHtmlType());
                }
                genTableColumnService.updateById(column);
            }
            else
            {
                genTableColumnService.save(column);
            }
        });

        List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
        if (StringUtils.isNotEmpty(delColumns))
        {
            genTableColumnMapper.deleteGenTableColumns(delColumns);
        }
    }

    /**
     * 批量生成代码（下载方式）
     * 
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String[] tableNames) throws TemplateException, IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames)
        {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 查询表信息并生成代码
     */
    private void generatorCode(String tableName, ZipOutputStream zip) throws IOException, TemplateException {
        GenTableInfoVO genTableInfoVO = this.getGenTableInfo(tableName);

        Map<String, Object> context = TemplateUtils.prepareContext(genTableInfoVO);
        List<String> templates = TemplateUtils.getTemplateList(genTableInfoVO.getTplCategory());

        for (String template : templates) {
            try {
                String templateStr = FreeMarkerUtils.processTemplate(template, context);
                String fileName = TemplateUtils.getFileName(template, genTableInfoVO);

                zip.putNextEntry(new ZipEntry(fileName));
                IOUtils.write(templateStr, zip, StandardCharsets.UTF_8);
                zip.closeEntry();
            } catch (IOException | TemplateException e) {
                log.error("生成代码失败，表名 [{}]，模板 [{}]", genTableInfoVO.getTableName(), template, e);
                throw e; // 向上抛出，让外层感知错误
            }
        }
    }


    /**
     * 获取表生成信息
     * @param tableName 表名
     * @return 表生成信息
     */
    private GenTableInfoVO getGenTableInfo(String tableName) {
        // 查询表信息
        GenTable table = selectGenTableByName(tableName);
        if (table != null) {
            GenTableInfoVO genTableInfoVO = new GenTableInfoVO();
            BeanUtils.copyProperties(table, genTableInfoVO);
            //获取表字段
            List<GenTableColumn> columnList = genTableColumnService.selectGenTableColumnListByTableId(table.getTableId());
            genTableInfoVO.setColumns(columnList);
            // 设置主键列信息
            setPkColumn(genTableInfoVO);

            //查询是否有子表 如果有子表把子表信息插入
            setChildrenTable(genTableInfoVO);

            return genTableInfoVO;
        }

        return null;
    }

    /**
     * 根据表名获取表信息
     * @param tableName 表名
     * @return 表信息
     */
    private GenTable selectGenTableByName(String tableName) {
        LambdaQueryWrapper<GenTable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GenTable::getTableName, tableName);
        return genTableMapper.selectOne(queryWrapper, false);
    }

    @Override
    public List<GenTable> getChildrenTable(String tableName) {
        LambdaQueryWrapper<GenTable> qw = new LambdaQueryWrapper<>();
        qw.eq(GenTable::getParentTableName, tableName);
        return genTableMapper.selectList(qw);
    }

    /**
     * 修改保存参数校验
     * 
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTableInfoVO genTable) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory()))
        {
            if (StringUtils.isEmpty(genTable.getTreeCode()))
            {
                throw new BizException("树编码字段不能为空");
            }
            else if (StringUtils.isEmpty(genTable.getTreeParentCode()))
            {
                throw new BizException("树父编码字段不能为空");
            }
            else if (StringUtils.isEmpty(genTable.getTreeName()))
            {
                throw new BizException("树名称字段不能为空");
            }
            else if (GenConstants.TPL_CHILDREN.equals(genTable.getTplCategory()))
            {
                if (StringUtils.isEmpty(genTable.getParentTableName()))
                {
                    throw new BizException("关联父表的表名不能为空");
                }
                else if (StringUtils.isEmpty(genTable.getSubTableFkName()))
                {
                    throw new BizException("子表关联的外键名不能为空");
                }
                else if (StringUtils.isEmpty(genTable.getParentTablePK()))
                {
                    throw new BizException("子表关联的父表字段不能为空");
                }
            }
        }
    }

    /**
     * 设置主键列信息
     * 
     * @param table 业务表信息
     */
    public void setPkColumn(GenTableInfoVO table){
        for (GenTableColumn column : table.getColumns())
        {
            if (column.isPk())
            {
                table.setPkColumn(column);
                break;
            }
        }
        if (StringUtils.isNull(table.getPkColumn()))
        {
            table.setPkColumn(table.getColumns().get(0));
        }
    }

    /**
     * 设置子表信息
     * @param table 生成表
     */
    public void setChildrenTable(GenTableInfoVO table){
        List<GenTable> childrenTable = this.getChildrenTable(table.getTableName());
        if (!CollectionUtils.isEmpty(childrenTable)) {
            List<GenTableInfoVO> childrenInfoVO = new ArrayList<>();
            for (GenTable child : childrenTable) {
                GenTableInfoVO genTableInfoVO = new GenTableInfoVO();
                BeanUtils.copyProperties(child, genTableInfoVO);
                //获取表字段
                List<GenTableColumn> columnList = genTableColumnService.selectGenTableColumnListByTableId(child.getTableId());
                genTableInfoVO.setColumns(columnList);
                // 设置主键列信息
                setPkColumn(genTableInfoVO);
                childrenInfoVO.add(genTableInfoVO);
            }
            table.setChildrenTable(childrenInfoVO);
        }

    }

    /**
     * 获取代码生成地址
     * 
     * @param table 业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, String template)
    {
        String genPath = table.getGenPath();
        if (StringUtils.equals(genPath, "/"))
        {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + TemplateUtils.getFileName(template, table);
        }
        return genPath + File.separator + TemplateUtils.getFileName(template, table);
    }
}